package com.pushwish.server;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

public class PullwishFromGTalk extends HttpServlet {

	private static final long serialVersionUID = 379460891011536344L;
	private static final Logger log = Logger.getLogger(PullwishFromGTalk.class.getName());

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		XMPPService xmpp = XMPPServiceFactory.getXMPPService();
		Message message = xmpp.parseMessage(req);
		JID fromJid = message.getFromJid();
		String body = message.getBody();
		Message msg;

		try {
			URL url = new URL("http://d3viewer.appspot.com/comment/");
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setDoOutput(true);
			connection.setRequestMethod("POST");
			String security = URLEncoder.encode(fromJid.getId() + " says: " + body,
					"UTF-8");
			OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
			writer.write("message=" + security);
			writer.close();

			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				// OK
			} else {
				msg = new MessageBuilder().withRecipientJids(fromJid)
						.withBody("I can't connect to server.").build();
			}
		} catch (MalformedURLException e) {
			log.severe(e.getMessage());
		} catch (IOException e) {
			log.severe(e.getMessage());
		}

		if (body.contains("shutout") || body.contains("quiet") || body.contains("silence")) {
			ServerConfig.shutout = true;
			msg = new MessageBuilder().withRecipientJids(fromJid)
					.withBody("I'm quiet now.").build();
		} else if (body.contains("shout")) {
			ServerConfig.shutout = false;
			msg = new MessageBuilder().withRecipientJids(fromJid)
					.withBody("I will shout aloud.").build();
		} else {
			msg = new MessageBuilder().withRecipientJids(fromJid)
					.withBody("I can't understand you.").build();
		}
		// SendResponse status =
		xmpp.sendMessage(msg);
		// messageSent = (status.getStatusMap().get(copy2jid) ==
	}
}
